<template>
  <BasePage>
    <!-- 头部 -->
    <BasePageHeader :title="pageTitle">
      <BaseBreadcrumb>
        <BaseBreadcrumbItem :title="$t('general.home')" to="/home" />
        <BaseBreadcrumbItem :title="$t('document.title')" to="/document" />
        <BaseBreadcrumbItem :title="$t('document.new')" to="#" active />
      </BaseBreadcrumb>

    </BasePageHeader>

    <form
      class="mt-6"
      action="submit"
      @submit.prevent="submitForm"
    >
      <BaseCard class="w-full">
        <BaseInputGrid layout="one-column">
          <!-- 标题 -->
          <BaseInputGroup
            :label="$t('document.cloumn.title')"
            :content-loading="isFetchingInitialData"
            required
            :error="
              v$.title.$error && v$.title.$errors[0].$message
            "
          >
            <BaseInput
              v-model="documentStore.currentDoc.title"
              :content-loading="isFetchingInitialData"
              :invalid="v$.title.$error"
              @input="v$.title.$touch()"
            />
          </BaseInputGroup>

          <!-- 型号 -->
          <BaseInputGroup
            :label="$t('document.cloumn.termodel')"
            :content-loading="isFetchingInitialData"
            required
            :error="
              v$.termodel.$error && v$.termodel.$errors[0].$message
            "
          >
            <BaseMultiselect
              v-model="documentStore.currentDoc.termodel"
              :content-loading="isFetchingInitialData"
              :options="termodelStore.termodels"
              :searchable="false"
              :allow-empty="false"
              label="model"
              value-prop="id"
              :placeholder="$t('document.select_model')"
              track-by="model"
              :invalid="v$.termodel.$error"
            />
          </BaseInputGroup>

          <!-- 状态 -->
          <BaseInputGroup
            :label="$t('general.status.title')"
            :content-loading="isFetchingInitialData"
            required
          >
            <div class="flex flex-row gap-8">
              <BaseRadio
                id="no_act"
                v-model="documentStore.currentDoc.status"
                :label="$t('general.status.code.usable')"
                size="sm"
                name="status"
                value="1"
                class="mt-2"
              />
              <BaseRadio
                id="yes_act"
                v-model="documentStore.currentDoc.status"
                :label="$t('general.status.code.unusable')"
                size="sm"
                name="status"
                value="0"
                class="mt-2"
              />
            </div>

          </BaseInputGroup>
          <!-- 内容 -->
          <BaseInputGroup
            :label="$t('document.detail.content')"
            :content-loading="isFetchingInitialData"
            required
          >

            <!-- 列表 -->
            <draggable 
              v-model="documentStore.currentDoc.detail" 
              item-key="id"
              handle=".handle"
              @change="changedraggable"
              class="w-full"
            >
              <template #item="{element, index}">
                <div class="flex justify-start w-full mb-4">
                  <div
                    class="
                      flex
                      items-center
                      justify-center
                      w-5
                      h-5
                      text-gray-300
                      cursor-move
                      handle
                      mr-2
                    "
                  >
                    <DragIcon />
                  </div>

                  <Detail 
                    v-model:content="element.content" 
                    v-model:title="element.title"
                    v-model:images="element.images"
                    :index="index"
                    @add-detail="addDetail"
                    @del-detail="delDetail"
                    @handle-attachment-upload="handleAttachmentUpload"
                    @inputDetail="v$.detail.$touch()"
                    :invalid="v$.detail.$error && v$.detail.$errors[0].$message[index].length"
                    :error="v$.detail.$error && v$.detail.$errors[0].$message[index][0]"
                  />
                </div>
                
              </template>
            </draggable>

          </BaseInputGroup>


          <!-- 提交 -->
          <div>
            <BaseButton
              :content-loading="isFetchingInitialData"
              type="submit"
              :loading="isSaving"
            >
              <template #left="slotProps">
                <BaseIcon
                  v-if="!isSaving"
                  name="SaveIcon"
                  :class="slotProps.class"
                />
              </template>

              {{ isEdit ? $t('general.update') : $t('general.save') }}
            </BaseButton>
          </div>

        </BaseInputGrid>
      </BaseCard>

    </form>
  </BasePage>

  <AttachmentUploadModal/>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
// 校验
import { required, maxLength, helpers } from '@vuelidate/validators'
import { useVuelidate } from '@vuelidate/core'
// pinia
import { useNotificationStore } from '@/stores/components/notification'
import { useDocumentStore } from '@/stores/document'
import { useTermodelStore } from '@/stores/termodel'
import { useAttachmentStore } from '@/stores/attachment'
import { useModalStore } from '@/stores/components/modal'
// 拖动
import draggable from 'vuedraggable'
import DragIcon from '@/components/icons/DragIcon.vue'
// compontent
import Detail from './Detail.vue'
import AttachmentUploadModal from '@/biz-components/modals/AttachmentUploadModal.vue'

const route = useRoute()
const router = useRouter()
const { t } = useI18n()

const notificationStore = useNotificationStore()
const documentStore = useDocumentStore()
const termodelStore = useTermodelStore()
const attachmentStore = useAttachmentStore()
const modalStore = useModalStore()
// 初始化
const isFetchingInitialData = ref(false)
const isSaving = ref(false)
// 编辑 or 添加
const isEdit = computed(() => route.name === 'document.edit')

async function initData() {
  isFetchingInitialData.value = true
  await termodelStore.fetchItems({skip: 0, limit: 100})
  // 修改
  if (isEdit.value) {
    let id = route.params.id
    await documentStore.fetchItem(id)
  } else { // 添加
    documentStore.resetCurrentDoc() 
  }

  isFetchingInitialData.value = false
}
initData()

const pageTitle = computed(() =>
  isEdit.value ? t('document.edit') : t('document.new')
)

// 详情 detail
function addDetail() {
  const len = documentStore.currentDoc.detail.push({
      "title": "",
      "content": "",
      "images": [],
      "sort": null,
      "status": 1,
    }) //(Object.assign({}, documentStore.detailTemp))
  // console.log('addDetail', len)
  documentStore.currentDoc.detail[len-1].sort = len
}

function delDetail(key) {
  if (documentStore.currentDoc.detail.length > 1){
    documentStore.currentDoc.detail.splice(key, 1)
  } else {
    // console.log('只有一个内容')
    // 提示不能少于一个， 至少一个内容
    notificationStore.showNotification({
      type: 'error',
      message: t('errors.no_empty'),
    })
  }

}
// ---------------- 提交表单 ------------------
/**
 * "title": '',
      "termodel": null,
      "status": '1',
      "detail": [{
        "content": "",
        "images": [],
        "sort": 1,
        "status": 1,
      }],
 */

const rules = {
  title: {
    required: helpers.withMessage(t('validation.required'), required),
  },
  termodel: {
    required: helpers.withMessage(t('validation.required'), required),
  },
  detail: {
    required: helpers.withMessage(t('validation.required'), required),
    $each: helpers.forEach({
      content: {
        required: helpers.withMessage(t('validation.required'), required),
        maxLength: helpers.withMessage(
          t('validation.content_maxlength'),
          maxLength(2000)
        ),
      }
    })
  },
}

const v$ = useVuelidate(
  rules,
  computed(() => documentStore.currentDoc)
)

// 
function submitForm() {
  v$.value.$touch()

  if (v$.value.$invalid) {
    // v$.detail.$errors[0].$message[key].length
    console.log('submitForm invalid', v$.value.detail)
    return true
  }

  // 
  let document = Object.assign({}, documentStore.currentDoc)
  document.detail.forEach((d, key) => {
    d.images = Array.isArray(d.images) ? JSON.stringify(d.images) : JSON.stringify([])
    d.sort = key+1
    console.log(key, d)
  })
  console.log('submitForm', document)

  // return false
  isSaving.value = true

  if (isEdit.value) { // 修改
    const data = Object.assign({
        id: route.params.id
      }, document)

    documentStore.updateItem(data).then(function() {
      notificationStore.showNotification({
        type: 'success',
        message: t('general.action.update_suc'),
      })

      router.push('/document')
    })
  } else { // 添加
    documentStore.addItem(document).then(function() {
      notificationStore.showNotification({
        type: 'success',
        message: t('general.action.insert_suc'),
      })

      router.push('/document')
    })
  }

  isSaving.value = false
}

// ceshi
function changedraggable(e) {
  console.log('changedraggable:', e)
}

// 图片上传弹窗
function handleAttachmentUpload(id) {
  attachmentStore.currentDocDetailID = id
  modalStore.openModal({
    title: t('attachment.upload'),
    componentName: 'AttachmentUploadModal',
    size: 'sm',
    refreshData: handleUploaded
  })
}

function handleUploaded() {
  // console.log('handleUploaded: ', documentStore.currentDoc.detail, '-', attachmentStore.currentDocDetailID, '-')
  if (attachmentStore.currentAttachment && attachmentStore.currentDocDetailID != null) {
    documentStore.currentDoc.detail[attachmentStore.currentDocDetailID].images.push({
      id: attachmentStore.currentAttachment.id,
      url: attachmentStore.currentAttachment.url,
    })
  }
  
  attachmentStore.currentDocDetailID = null
  attachmentStore.currentAttachment = {}
}


</script>
